package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.BehaviorCollectionService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.rides.RedisCacheService;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BehaviorCollectionServiceImpl implements BehaviorCollectionService {

    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult BehaviorCollection(CollectionBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getEntryId() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断登录用户
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //如果是收藏
        if (dto.getOperation() == 0){
            redisCacheService.hPut("BEHAVIOR_COLLECTION_"+dto.getEntryId(),user.getId().toString(), JSON.toJSONString(dto));

            //向kafka发送消息,进行数据聚合
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setArticleId(dto.getEntryId());
            mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
            mess.setAdd(1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));


        }else {
            redisCacheService.hDelete("BEHAVIOR_COLLECTION_"+dto.getEntryId(),user.getId().toString());

            //向kafka发送消息,进行数据聚合
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setArticleId(dto.getEntryId());
            mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
            mess.setAdd(-1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));

        }
        return ResponseResult.okResult(null);


    }
}
